import { ArgumentsHost, BadRequestException, Catch, ExceptionFilter, HttpException } from "@nestjs/common";
import { I18nService, I18nValidationException } from "nestjs-i18n";

@Catch(HttpException)
export class AdminExceptionFilter implements ExceptionFilter{
    constructor(private readonly i18n: I18nService){}
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp()
        const response = ctx.getResponse()
        const request = ctx.getRequest()
        let status = exception.getStatus()
        let message = exception.message
        if (exception instanceof BadRequestException) {
            const exceptionBody: any = exception.getResponse()
            console.log('exceptionBody', exceptionBody)
            if (typeof exceptionBody === 'object' && exceptionBody.message){
                message = exceptionBody.message.join(',')
                status = exceptionBody.statusCode
            }
        } else if (exception instanceof I18nValidationException) {
            const errors = exception.errors
            message = errors.map(error => this.formatErrorMessage(error, request.i18nLang)).join(';')
        }
        response.status(status).render('error', {
            message
        })
    }
    formatErrorMessage(error, lang){
        const {property, value, constraints} = error
        const constraintValues = Object.values(constraints)
        const formattedMessages = constraintValues.map((constraintValue: any) => {
            const [key, params] = constraintValue.split('|')
            if (params) {
                const parsedParams = JSON.parse(params)
                return this.i18n.translate(key, {
                    lang,
                    args: parsedParams
                })
            }
        })
        return `${property}: ${value} ${formattedMessages.join(',')}`
    }
}

  